<script lang="ts" setup name="MobileForm">
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
import { setTenantIdCache, setToken } from '@/utils/auth'
import { AuthApi } from '@/api/auth'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

const { t } = useI18n()
const message = useMessage()
const { currentRoute, push } = useRouter()
const formSmsLogin = ref()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { validForm } = useFormValid(formSmsLogin)
const { handleBackLogin, getLoginState } = useLoginState()

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE)

const rules = {
  tenantName: [required],
  mobileNumber: [required],
  code: [required]
}

const loginData = reactive({
  codeImg: '',
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  token: '',
  loading: {
    signIn: false
  },
  loginForm: {
    uuid: '',
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    mobileNumber: '',
    code: ''
  }
})

const smsInfo = reactive({
  smsCode: {
    mobile: '',
    scene: 21
  },
  loginSms: {
    mobile: '',
    code: ''
  }
})

const mobileCodeTimer = ref(0)
const redirect = ref<string>('')
const getSmsCode = async () => {
  await getTenantId()
  smsInfo.smsCode.mobile = loginData.loginForm.mobileNumber
  await AuthApi.Sms.code(smsInfo.smsCode).then(async () => {
    message.success(t('sign.fields.code', 'send'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await AuthApi.Tenant.getIdByName(loginData.loginForm.tenantName)
    setTenantIdCache(res)
  }
}
// 登录
const signIn = async () => {
  await getTenantId()
  const data = await validForm()
  if (!data) return
  smsInfo.loginSms.mobile = loginData.loginForm.mobileNumber
  smsInfo.loginSms.code = loginData.loginForm.code
  await AuthApi.Sms.signIn(smsInfo.loginSms)
    .then(async (res) => {
      setToken(res)
      if (!redirect.value) {
        redirect.value = '/'
      }
      push({ path: redirect.value })
    })
    .catch(() => {})
}
</script>

<template>
  <el-form v-show="getShow" ref="formSmsLogin" :model="loginData.loginForm" :rules="rules" class="login-form" label-position="top" label-width="120px" size="large">
    <el-row>
      <!-- 租户名 -->
      <el-col :span="24">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
          <el-input v-model="loginData.loginForm.tenantName" :placeholder="t('sign.fields.tenant', 'placeholder')" :prefix-icon="iconHouse" type="primary" link />
        </el-form-item>
      </el-col>
      <!-- 手机号 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="mobileNumber">
          <el-input v-model="loginData.loginForm.mobileNumber" :placeholder="t('sign.fields.phone', 'placeholder')" :prefix-icon="iconCellphone" />
        </el-form-item>
      </el-col>
      <!-- 验证码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="code">
          <el-input v-model="loginData.loginForm.code" :placeholder="t('sign.fields.code', 'placeholder')" :prefix-icon="iconCircleCheck">
            <!-- <el-button class="w-[100%]"> -->
            <template #append>
              <span v-if="mobileCodeTimer <= 0" class="getMobileCode" style="cursor: pointer" @click="getSmsCode">
                {{ t('sign.fields.code', 'button') }}
              </span>
              <span v-if="mobileCodeTimer > 0" class="getMobileCode" style="cursor: pointer">
                {{ t('sign.fields.code', 'restart', [mobileCodeTimer]) }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <!-- 登录按钮 / 返回按钮 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :title="t('sign.in', 'action')" class="w-[100%]" type="primary" @click="signIn()" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :title="t('sign', 'backLogin')" class="other-button w-[100%]" @click="handleBackLogin()" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style lang="scss" scoped></style>
